<?php
namespace Alipaylogin;
// 使用 Guzzle 做请求操作
use GuzzleHttp\Client;
// 支付宝APP 第三方登录
// 特点：相比微信，支付宝所有敏感信息都在服务端完成， 保证了安全
//
// 流程：
// 1.服务端到APP infoStr
// 2.APP端 通过infoStr 获得 auth_code
// 3.服务端通过 auth_code 拿到请求 token
// 4.服务端通过 token 获得用户信息
class Alipaylogin{
    protected $app_id = '2021002141621447';
    protected $pid = '2088141293112185';
    protected $private_key = 'MIIEowIBAAKCAQEArkFyjwazmvjb6tfjKOf0DAm1jQ7XJpwlaV0IPKw1XIDir9+Z3e/ulaiv9r2zgKYlTvwuT2F41YBylDIZiwkWqW7Wpw/+jK5/mUhRdD1mrMFZ0bk1yI0DWj2P/G19lsYrLv+tQ0NucIv9t8LgjIgMrnO1RrpKQ12JpVGBqHsckXFdEXwNIRV7eGfUjKltDOJYKhOGU1utPbaB4qP5Vqv8ylQ6946v1YtORXxh7ZFpzOaQTjz3LrbXXOFl+0w9m/iZTwCODFX9MM4KeGfNtiTQBakf8qguMtKjjRmpnVfNJKRcHnamdv8/4dpCMDBXt/PpU8seA1TLyzsBdq9GUi1pawIDAQABAoIBAEKZkQdJMGwSoTrouFFyFbxkGZeIDIMdOs9CV1uZFev89qbxdwV0JmPczSQo7OpGlgvSJoEAaAZxyVkKrOiO2LJ5QmEno8pxByO2mCstLIjqfUHC3+N+wcFDtjxsPIvbwbV80uPaaeNqHdaWDOypMu+aGbamjKuinHEq7btPEmQjpM59XmfeKMSegBAriBSW736fRmgWCtBkA99JqD9ehxuFpV29N7umnToXbNAIbWO+XumEI0LcHPeRvwwI4wjoxJVNOHu5wcqycJajcr0ipLsMtR7Nb/MtnHLArt7XvQ02Nm/2qLMsqjmROO0vXvvfJt9hz1+w/AsRMdH+wkUajkECgYEA8j3YBeYR2BDrJbvPfBnQBAPatdmJNLZ2jxdpCxqpPpan5yOI4Saw7abcOkWC4WWBNjslCpVufdwUcAIYBk1GNOpOnsGD2W6IPHy29wgaKQFefMvSsCYP2GpGqdkyNGGI4xbIx7vdW1a8X6y+FjNGGB0RhmGZhGtIFzWkY2/mCv8CgYEAuCcZOfOrkrI51aq2iQcIJfpo1vERpNwhu/qYosG0rMPvsOvz7VXUe0RkuXIKJNsNWQNIMoQxs/ombHiCeQbJzVClCe/1kYVl0ngXw5+DuW/ggdaZKf29z01ezBjJKir+p6dPbU6T+o5FL/WVneCZgxA1JiEdWzOpXDL5Lo6V/ZUCgYEApKRx8bhogmElYZUftWpZ3pC8EwMSZThqpmCz7W8mfrqozclyHA1PDYdugVCDXyy9QJ28VFAyM+rkHSjfKVFWGVrzKqW+NocQo4PkW0wvc5VRoiJqRXzpIh9Bfel4XO+5uRbgShien5j5GVHwNGiPCI6hPaOSUtUTv2qfG1KPmQMCgYA1CXW3fhltD42enyMhRfgvz/X/6cA2JfxFQoBRZ86cb3YKE3rWYQDoW6NS0ahgQwKOH2bcvbv+5M3KMc8KAk1+p3pQ6V5lgfD4dAQMIFX0w2b6ng7QzDatjM//oifV0Do1mPdEOPxfjjgY/vcPWE9+Mt3L1H+6858UYc3ofcJvHQKBgCpPGU8LKK3uoxnKvdGuiWcWJxgK5MIHVkcwPciEGtLB05kULqYms5MShtMwal2Q5KKiVVPlcN1yAHUfrSqsP6dLRQn3n7M7kHl8v2wbc17804Fx98XjnQM6kVQ0ex/AaeBbw9TibG8MYh/Oz1ZCN6dBI1cv8A2+nLF9j9X8CmAd';
    /**
     * InfoStr APP登录需要的的infostr
     *
     * @return String
     */
    public function infoStr()
    {
        $infoStr = http_build_query([
            'apiname' => 'com.alipay.account.auth',
            'method' => 'alipay.open.auth.sdk.code.get',
            'app_id' => $this->app_id,
            'app_name' => 'mc',
            'biz_type' => 'openservice',
            'pid' => $this->pid,
            'product_id' => 'APP_FAST_LOGIN',
            'scope' => 'kuaijie',
            'target_id' => mt_rand(999, 99999), //商户标识该次用户授权请求的ID，该值在商户端应保持唯一
            'auth_type' => 'AUTHACCOUNT', // AUTHACCOUNT代表授权；LOGIN代表登录
            'sign_type' => 'RSA2',
        ]);
        $infoStr .= '&sign='.$this->enRSA2($infoStr);
        return $infoStr;
    }
    /**
     * AlipayToken 获得用户 请求token, 通过它获得 用户信息
     *
     * 需要按照支付宝加签流程来。
     */
    public function userInfo($app_auth_token)
    {
        $infoArr = [
            'method' => 'alipay.system.oauth.token',
            'app_id' => $this->app_id,
            'charset' => 'utf-8',
            'sign_type' => 'RSA2',
            'timestamp' => date('Y-m-d H:i:s'),
            'version' => '1.0',
            'code' => $app_auth_token,
            'grant_type' => 'authorization_code',
        ];
        $signStr = $this->myHttpBuildQuery($infoArr);
        $sign = urlencode($this->enRSA2($signStr));
        $qureStr = $signStr.'&sign='.$sign;
        $res = new Client();
        $body = $res->get('https://openapi.alipay.com/gateway.do?'.$qureStr)->getBody()->getContents();
        $body = json_decode($body);
        if (!isset($body->alipay_system_oauth_token_response->access_token)) {
            return '接口异常';
        } else {
            $autho_token = $body->alipay_system_oauth_token_response->access_token;
            $userinfo = $this->aliPayUserInfo($autho_token);
            return $userinfo; // 或则 返回 json_encode($userinfo) 根据实际需求来
        }
    }
    /**
     * AliPayUserInfo 通过 token 获取用户信息
     */
    private function aliPayUserInfo($autho_token)
    {
        $infoArr = [
            'method' => 'alipay.user.info.share',
            'app_id' => $this->app_id,
            'charset' => 'utf-8',
            'sign_type' => 'RSA2',
            'timestamp' => date('Y-m-d H:i:s'),
            'version' => '1.0',
            'auth_token' => $autho_token,
        ];
        $signStr = $this->myHttpBuildQuery($infoArr);
        $sign = urlencode($this->enRSA2($signStr));
        $qureStr = $signStr.'&sign='.$sign;
        $res = new Client();
        $body = $res->get('https://openapi.alipay.com/gateway.do?'.$qureStr)->getBody()->getContents();
        $body = json_decode($body);
        if (!isset($body->alipay_user_info_share_response)) {
            return '接口异常';
        }
        $body = $body->alipay_user_info_share_response;
        return $body;
    }
    /**
     * enRSA2 RSA加密
     *
     * @param String $data
     * @return String
     */
    private function enRSA2($data)
    {
        $str = chunk_split(trim($this->private_key), 64, "\n");
        $key = "-----BEGIN RSA PRIVATE KEY-----\n$str-----END RSA PRIVATE KEY-----\n";
        // $key = file_get_contents(storage_path('rsa_private_key.pem')); 为文件时这样引入
        $signature = '';
        $signature = openssl_sign($data, $signature, $key, OPENSSL_ALGO_SHA256)?base64_encode($signature):NULL;
        return $signature;
    }
    /**
     * myHttpBuildQuery 返回一个 http Get 传参数组
     * 之所以不用 自带函数 http_build_query 时间带 ‘:’ 会被转换
     *
     * @param Array
     * @return String
     */
    private function myHttpBuildQuery($dataArr)
    {
        ksort($dataArr);
        $signStr = '';
        foreach ($dataArr as $key => $val) {
            if (empty($signStr)) {
                $signStr = $key.'='.$val;
            } else {
                $signStr .= '&'.$key.'='.$val;
            }
        }
        return $signStr;
    }
}